package com.mrx.xcitools.service;

import com.mrx.xcitools.dao.RepositoryConfigMapper;
import com.mrx.xcitools.model.RepositoryConfig;
import com.mrx.xcitools.utils.GitUtils;
import com.mrx.xcitools.utils.MavenUtils;
import jakarta.annotation.Resource;
import org.eclipse.jgit.api.Git;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.io.File;

/**
 * @author Mr.X
 * @since 2024-03-10 下午 5:37:25
 */
@Service
public class XCIService {

    @Resource
    private RepositoryConfigMapper repositoryConfigMapper;

    @Resource
    private MavenBuildLogService mavenBuildLogService;

    private static final Logger logger = LoggerFactory.getLogger(XCIService.class);

    public void addRepositoryConfig(RepositoryConfig config) {
        config.setDiskPath(cloneProject(config));
        logger.info("addRepositoryConfig: {}", config);
        repositoryConfigMapper.insert(config);
    }

    public void buildProject(Integer id) {
        RepositoryConfig project = repositoryConfigMapper.selectById(id);
        if (!StringUtils.hasText(project.getDiskPath())) {
            project.setDiskPath(cloneProject(project));
        }
        Assert.notNull(project, "Project not exists");
        logger.info("buildProject: {}", project);
        Assert.isTrue(MavenUtils.makePackage(project.getDiskPath(), it -> mavenBuildLogService.collectLogs(id, it)), "Build Failed");
        logger.info("buildProject succeed: {}", project);
    }

    private String cloneProject(RepositoryConfig config) {
        String dir = config.getDir();
        File projectDir = GitUtils.getProjectDir(dir);
        if (projectDir.exists()) {
            logger.info("project cloned, skipping");
            return projectDir.getAbsolutePath();
        }
        logger.info("cloning project: {}", config);
        try (Git cloned = GitUtils.cloneRepository(config.getGitUrl(), config.getBranch(), dir)) {
            return GitUtils.getProjectDir(cloned);
        }
    }

}
